<template>
    <div>
        <Spin fix v-if="ifSpin">
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
            <div>附件下载中</div>
        </Spin>
        <Form ref="queryForm" :model="dataToQuery" :label-width="120">
            <Row :gutter="16" class="query-form" >
                <i-col span="8">
                    <FormItem label="二级集团：">
                        <Select v-model="dataToQuery.twoLevelOrgId" filterable>
                            <Option v-for="item in twoLevelOrgList" :value="item.orgId" :key="item.orgId">{{ item.orgName }}</Option>
                        </Select>
                    </FormItem>
                </i-col>
                <i-col span="8">
                    <FormItem label="所属单位：">
                        <company-select v-model="dataToQuery.orgName" style="width:100%" />
                        <!-- <cascaderDom ref="queryOrgCascader" @setOrgInfo="setOrgId" @setOrgname="setOrgName"
                                        :orgTree="true"></cascaderDom> -->
                    </FormItem>
                </i-col>
                <i-col span="8" v-if="!switchFlag">
                    <div style="float: right;">
                        <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch" type="text" >展开<Icon type="ios-arrow-down"/></Button>
                        <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reseter">重置</Button>
                        <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                    </div>
                </i-col>
                <i-col span="8" v-else>
                    <FormItem label="姓名：">
                        <Input  class='' type='text' v-model='dataToQuery.userName'></Input>
                    </FormItem>
                </i-col>
            </Row>
            <Row v-show="switchFlag" :gutter="16" class="query-form">
                <i-col span="8">
                    <FormItem label="联系电话：">
                        <Input  class='' type='text' v-model='dataToQuery.mobileNumber'></Input>
                    </FormItem>
                </i-col>
                <i-col span="8">
                    <FormItem label="创建时间：">
                        <DatePicker v-model="dataToQuery.se_date" type="datetimerange" style="width: 100%" format="yyyy-MM-dd" placeholder="请选择创建时间（开始，结束）"></DatePicker>
                    </FormItem>
                </i-col>
                <i-col span="8">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text" >收起<Icon type="ios-arrow-up" /></Button>
                    <Button class="ivu-btn-reset" @click="reseter">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search"  @click="query">查询</Button>
                </i-col>
            </Row>      
        </Form>
        <Row type="flex" justify="start" class="query-form">
            <i-col>
                <Button icon="md-add" class="ivu-btn-add" @click="addInfo">新增</Button>
                <Button type="primary" class="ivu-btn-add" icon="md-cloud-download" :loading="buttonLoading" @click="exportFormSubmit">导出</Button>
            </i-col>
        </Row>
        <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" no-data-text="没有查询到相关数据！"
         @on-sort-change="sortChange"
         :data="infos" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
        <Row type="flex" justify="end" >
            <i-col>
                <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                      @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </i-col>
        </Row>
        <Modal v-model="modal1" width="800" :mask-closable="false" :title="'防汛管理 ' + titleName">
            <Form ref="formCustom" :model="formData" :rules="ruleCustom" label-position="top">
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="创建人：" prop="userName">
                            <Input v-model="formData.userName" readonly/>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="联系电话：" prop="mobileNumber">
                            <Input v-model="formData.mobileNumber" />
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="创建时间：" prop="createDateStr">
                            <Input v-model="formData.createDateStr" readonly/>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="所属单位：" prop="orgName">
                            <Input v-model="formData.orgName" readonly/>
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="所属二级集团：" prop="twoLevelOrgName">
                            <Input v-model="formData.twoLevelOrgName"  readonly/>
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col span="24">
                        <FormItem label="防汛文件：" prop="orgName">
                            <Upload
                                    multiple
                                    ref="upload"
                                    type="drag"
                                    name="files"
                                    :show-upload-list="false"
                                    :format="['pdf', 'xlsx', 'xls', 'docx', 'doc']"
                                    :before-upload="beforeUpload"
                                    :action="fileUrl">
                                <div style="padding: 20px 0">
                                    <Icon type="ios-cloud-upload" size="52" style="color: #F27874"></Icon>
                                    <p><span style="color: red">*</span>点击将文件拖拽到这里上传</p>
                                </div>
                            </Upload>
                            <div v-for="(item, index) in fileList" :key="index">
                                <a>{{item.name}}</a>
                                <Button type="text" icon="md-trash" @click="removeFile(item.keyID)"  style="margin-left: 10px;margin-bottom: 3px"/>
                            </div>
                            <div v-for="(item, index) in modifyFile" :key="index">
                                <a @click.prevent="downloadFile(item)">{{item.fileName}}</a>
                                <Button type="text" icon="md-trash" @click.native="removeFile2(item)"  style="margin-left: 10px;margin-bottom: 3px"/>
                            </div>
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button @click="saveInfo" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
                <Button @click="modal1 = false" class="ivu-btn-cancel" >取消</Button>
            </div>
        </Modal>
        <Modal v-model="modal2" width="800" :mask-closable="false" title="防汛管理详情">
            <Form ref="formCustom" :model="formData" :rules="ruleCustom">
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="创建人：" prop="userName">
                            {{formData.userName}}
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="联系电话：" prop="mobileNumber">
                            {{formData.mobileNumber}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16" class="code-row-bg2">
                    <i-col span="12">
                        <FormItem label="创建时间：" >
                            {{formData.createDateStr}}
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="所属单位：" >
                            {{formData.orgName}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col>
                        <FormItem label="所属二级集团：">
                            {{formData.twoLevelOrgName}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col span="24">
                        <FormItem label="回执文件：" prop="orgName">
                            <div v-for="(item, index) in modifyFile" :key="index">
                                <a @click.prevent="downloadFile(item)">{{item.fileName}}</a>
                            </div>
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button @click="modal2 = false" class="ivu-btn-cancel" >取消</Button>
            </div>
        </Modal>
    </div>
</template>

<script>

    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {Api} from '@/api/index.js'

    export default {
        name: "floodPrevention",
        components:{
            cascaderDom
        },
        data(){
            const validatePhone = (rule, value, callback) => {
                if(!this.formData.mobileNumber) {
                    return callback(new Error('手机号不能为空'));
                } else if(!/^1[345789]\d{9}$/.test(this.formData.mobileNumber)) {
                    callback('手机号格式不正确');
                } else {
                    callback();
                }
            };
            return{
                ifSpin: false,
                isUpdate:false,
                fileUrl: '',
                buttonLoading: false,
                switchFlag: false,
                tableHeight: '',
                loading: false,
                dataToQuery: {
                    se_date: []
                },
                ruleCustom: {
                    userName: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    mobileNumber: [
                        {
                            required: true,
                            validator: validatePhone,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    createDateStr: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    orgName: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                },
                modal1: false,
                modal2: false,
                titleName: '',
                formData: {},
                currentUser: sessionStorage('userId').getObject('userId'),
                pageSizeArray: [10, 20, 50],
                fileList: [],
                modifyFile: [],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                columns: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        title: '所属二级集团',
                        align: 'center',
                        key: 'twoLevelOrgName',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.twoLevelOrgName || '--')
                            ]);
                        }
                    },
                    {
                        title: '所属单位',
                        align: 'center',
                        key: 'orgName',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.orgName || '--')
                            ]);
                        }
                    },
                    {
                        title: '创建人',
                        align: 'center',
                        key: 'userName',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.userName || '--')
                            ]);
                        }
                    },
                    {
                        title: '联系电话',
                        align: 'center',
                        key: 'mobileNumber',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.mobileNumber || '--')
                            ]);
                        }
                    },
                    {
                        title: '创建时间',
                        align: 'center',
                        key: 'createDateStr',sortable: "custom", 
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span', params.row.createDateStr || '--')
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        align: 'center',
                        fixed: 'right',
                        minWidth: 180,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.modal2 = true;
                                            this.updateInfo(params.row);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.modal1= true;
                                            this.updateInfo(params.row);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        color: 'red',
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteInfo(params.row);
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    },

                ],
                infos: [],
                twoLevelOrgList: [],
                buttonLoading: false
            }
        },
        mounted(){
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.queryTwoLevelOrg();
            this.query();
            this.$Loading.config({
                color: '#5cb85c',
                failedColor: 'red',
                height: 5
            });
        },
        watch: {
            "modal1":function(qw,er){
                if(!qw){
                    this.formData = {};
                    this.fileList = [];
                    this.modifyFile = [];
                }
            },
            "modal2":function(qw,er){
                if(!qw){
                    this.formData = {};
                    this.fileList = [];
                    this.modifyFile = [];
                }
            },
        },
        methods: {
            sortChange(data) {
                if (data.order === 'asc'||data.order ==='desc') {
                    let order = data.key.replace('Str','')
                    this.dataToQuery.dynamicSort = order +' '+ data.order
                    this.query()
                }
            },
            query(){
                this.loading = true;
                let data = {
                    orgId: this.currentUser.companyId,
                    startPage: this.pagedata.currentPage,
                    pageSize: this.pagedata.pageSize,
                }
                if(this.dataToQuery.se_date.length!=0){
                    if(this.dataToQuery.se_date[0] != '' && this.dataToQuery.se_date[1] != ''){
                        data.startDate = this.formatDate(new Date(this.dataToQuery.se_date[0]), 'yyyy-MM-dd');
                        data.endDate = this.formatDate(new Date(this.dataToQuery.se_date[1]), 'yyyy-MM-dd');
                    }
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.dataToQuery)));
                this.$http.get(Api.floodPrevention, {
                    params: data
                }).then(function(res){
                    this.infos = res.data.data;
                    this.pagedata.total = res.data.totalSize;
                    this.loading = false;
                }, function(res){
                    this.$Message.error('请求失败');
                    this.loading = false;
                });
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            reseter(){
                this.dataToQuery = {
                    se_date: []
                };
                setTimeout(() => {
                    this.$refs.queryOrgCascader && this.$refs.queryOrgCascader.setCurrentOrg();
                }, 100);
                this.query();
            },
            switchQuery(flag){
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 44;
                } else {
                    this.tableHeight = this.tableHeight - 44;
                }
            },
            addInfo(){
                this.isUpdate = false;
                this.modal1 = true;
                this.titleName = "新增";
                this.formData = {
                    userName: this.currentUser.userName,
                    userId: this.currentUser.userId,
                    orgName: this.currentUser.companyName,
                    orgId: this.currentUser.companyId,
                    mobileNumber: this.currentUser.mobileNumber,
                    createDate: new Date(),
                    createDateStr: this.formatDate(new Date()),
                    id: this.uuid(),
                    twoLevelOrgId: this.currentUser.twoLevelOrgId,
                    twoLevelOrgName: this.currentUser.twoLevelOrgName
                };
                this.fileUrl = Api.uploadPTWFiles  + '/' + this.formData.id + '/files/guideFile'
            },
            updateInfo(row){
                this.isUpdate = true;
                this.formData = row;
                this.formData.updateUserId = this.currentUser.userId;
                this.titleName = "修改";
                this.fileUrl = Api.uploadPTWFiles  + '/' + this.formData.id + '/files/guideFile'
                this.$http.get(this.fileUrl,{
                    params: {},
                }).then((res) => {
                    res.data.data.map((i) =>{
                        this.modifyFile.push(i);
                    })
                })
            },
            setOrgId(data) {
                this.dataToQuery.orgId= data[data.length - 1];
            },
            setOrgName(data) {
                this.dataToQuery.orgName = data;
            },
            saveInfo(){
                this.$refs['formCustom'].validate((valid) => {
                    if(valid) {
                        this.buttonLoading = true;
                        this.fileList.map((i)=>{
                            this.$refs.upload.post(i);
                        })
                        if(this.isUpdate){
                            this.$http.put(Api.floodPrevention, this.formData).then(function(response){
                                this.buttonLoading = false;
                                this.modal1 = false;
                                this.query();
                                this.$Message.success({  content: '保存成功', duration: 4 });
                            });
                        }else{
                            this.$http.post(Api.floodPrevention, this.formData).then(function(response){
                                this.buttonLoading = false;
                                this.modal1 = false;
                                this.query();
                                this.$Message.success({  content: '保存成功', duration: 4 });
                            });
                        }
                    }
                })
            },
            deleteInfo(row){
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该条信息</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.delete(Api.floodPrevention, {params:{
                                id: row.id,
                                updateUserId: this.currentUser.userId
                            }}).then((res) => {
                            this.$Message.success({content:'删除成功',duration: 4});
                            this.query();
                        })
                    },
                    cancelText: '取消'
                });
            },
            beforeUpload (file) {
                if(file.type.indexOf("pdf") == -1){
                    this.$Notice.warning({
                        title: '请上传PDF格式附件！',
                    });
                }else{
                    let keyID = Math.random().toString().substr(2);
                    file['keyID'] = keyID;
                    this.fileList.push(file);
                }
                return false;
            },
            downloadFile(file){
                this.$Loading.start();
                let url = Api.interestedPartiesUserFile + '/file/' + file.id;
                this.$http.get(url, {
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {
                    this.$Loading.finish();
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = file.fileName //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                }, function(res){
                    this.$Loading.error();
                })
            },
            removeFile(keyID){
                this.fileList = this.fileList.filter(item => {
                    return item.keyID != keyID
                })
            },
            removeFile2(file){
                this.$http.delete(Api.uploadMongoFile + "/" + file.id).then((res) => {
                    this.modifyFile.splice(this.modifyFile.indexOf(file), 1);
                }).catch(e => {
                    this.$Message.error("附件删除失败");
                });
            },
            queryTwoLevelOrg(){
                this.$http.get(Api.twoPlusFourReceipt + '/twoLevelOrg').then((res) => {
                    if(res.data.status == 200){
                        this.twoLevelOrgList = res.data.data;
                    }
                }).catch(e => {
                    this.$Message.error("附件删除失败");
                });
            },
            exportFormSubmit(){
                this.buttonLoading = true;
                let data = {
                    orgId: this.currentUser.companyId
                }
                if(this.dataToQuery.se_date.length!=0){
                    if(this.dataToQuery.se_date[0] != '' && this.dataToQuery.se_date[1] != ''){
                        data.startDate = this.formatDate(new Date(this.dataToQuery.se_date[0]), 'yyyy-MM-dd');
                        data.endDate = this.formatDate(new Date(this.dataToQuery.se_date[1]), 'yyyy-MM-dd');
                    }
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.dataToQuery)));
                this.$http.get(Api.floodPrevention + '/export',{
                    params: data,
                    responseType: 'arraybuffer'
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "防汛管理("+ this.formatDate(new Date(), "yyyy-MM-dd")+ ").xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                    this.buttonLoading = false;
                })

            },
            formatDate(date, fmt) {
                if (typeof date == 'string') {
                    return date;
                }
                if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";
                if (!date || date == null) return null;
                let o = {
                    'M+': date.getMonth() + 1, // 月份
                    'd+': date.getDate(), // 日
                    'h+': date.getHours(), // 小时
                    'm+': date.getMinutes(), // 分
                    's+': date.getSeconds(), // 秒
                    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
                    'S': date.getMilliseconds() // 毫秒
                }
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
                for (let k in o) {
                    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
                }
                return fmt
            },
            uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for(let i = 0; i < 32; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
                let uuid = s.join("");
                return uuid
            },
        }
    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';

</style>
